package com.mars.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mars.common.constant.Constant;
import com.mars.common.response.PageInfo;
import com.mars.common.util.TokenUtils;
import com.mars.framework.exception.ServiceException;
import com.mars.framework.redis.RedisCache;
import com.mars.module.admin.response.UserInfoResponse;
import com.mars.module.app.request.AppLoginRequest;
import com.mars.module.app.request.AppRegisterRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import com.mars.module.admin.request.ApUserRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import com.mars.module.admin.mapper.ApUserMapper;
import org.springframework.beans.BeanUtils;
import com.mars.module.admin.entity.ApUser;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mars.module.admin.service.IApUserService;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * 用户业务层处理
 *
 * @author mars
 * @date 2024-02-24
 */
@Slf4j
@Service
@AllArgsConstructor
public class ApUserServiceImpl implements IApUserService {

    private final ApUserMapper baseMapper;

    private final TokenUtils tokenUtils;

    private final RedisCache redisCache;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ApUser add(ApUserRequest request) {
        ApUser entity = ApUser.builder().build();
        BeanUtils.copyProperties(request, entity);
        baseMapper.insert(entity);
        return entity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean delete(Long id) {
        return baseMapper.deleteById(id) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(List<Long> ids) {
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean update(ApUserRequest request) {
        ApUser entity = ApUser.builder().build();
        BeanUtils.copyProperties(request, entity);
        return baseMapper.updateById(entity) > 0;
    }

    @Override
    public ApUser getById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public PageInfo<ApUser> pageList(ApUserRequest request) {
        Page<ApUser> page = new Page<>(request.getPageNo(), request.getPageSize());
        LambdaQueryWrapper<ApUser> query = this.buildWrapper(request);
        IPage<ApUser> pageRecord = baseMapper.selectPage(page, query);
        return PageInfo.build(pageRecord);
    }


    @Override
    public List<ApUser> list(ApUserRequest request) {
        LambdaQueryWrapper<ApUser> query = this.buildWrapper(request);
        return baseMapper.selectList(query);
    }

    @Override
    public String login(AppLoginRequest request) {
        ApUser apUser = baseMapper.selectOne(Wrappers.lambdaQuery(ApUser.class).eq(ApUser::getAccount, request.getAccount()));
        if (Objects.isNull(apUser)) {
            throw new ServiceException("用户不存在");
        }
        if (!request.getPassword().equals(apUser.getPassword())) {
            throw new ServiceException("密码不正确");
        }
        // 更新登录时间
        apUser.setLoginTime(LocalDateTime.now());
        baseMapper.updateById(apUser);
        String token = tokenUtils.createToken(apUser.getId(), apUser.getAccount(),apUser.getHeadPortrait());
        redisCache.setCacheObject(Constant.USER_TOKEN_CACHE + apUser.getId(), token, 30, TimeUnit.DAYS);
        log.info("登录成功{}", token);
        return token;
    }

    @Override
    public void register(AppRegisterRequest request) {
        ApUser apUser = baseMapper.selectOne(Wrappers.lambdaQuery(ApUser.class).eq(ApUser::getAccount, request.getAccount()));
        if (Objects.nonNull(apUser)) {
            throw new ServiceException("当前账号已注册");
        }
        ApUser user = ApUser.builder().account(request.getAccount())
                .mobile(request.getMobile())
                .password(request.getPassword())
                .headPortrait(Constant.DEFAULT_AVATAR)
                .build();
        baseMapper.insert(user);
    }

    @Override
    public UserInfoResponse getUserInfo(Long userId) {
        ApUser apUser = baseMapper.selectById(userId);
        if (Objects.isNull(apUser)){
            throw new ServiceException("用户信息不存在");
        }
        UserInfoResponse response = new UserInfoResponse();
        BeanUtils.copyProperties(apUser,response);
        return response;
    }

    private LambdaQueryWrapper<ApUser> buildWrapper(ApUserRequest param) {
        LambdaQueryWrapper<ApUser> query = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getAccount())) {
            query.like(ApUser::getAccount, param.getAccount());
        }
        return query;
    }

}
